const isDevelopment = true,
  secondWindowUrl = 'http://client.smartorderkiosk.com/desk/#/secondPage',
  userAgent =
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0'

//创建副屏页面
export function createSecondaryWindow() {
  let url = secondWindowUrl
  // Get all displays
  const displays = screen.getAllDisplays()
  console.log('displays', displays)
  let externalDisplay = displays.find((display) => {
    // Find external display (not the primary one)
    return display.bounds.x !== 0 || display.bounds.y !== 0
  })

  //test
  if (isDevelopment) {
    externalDisplay = {
      bounds: {
        x: 100,
        y: 100,
        width: 800,
        height: 1280
      }
    }
  }
  if (!externalDisplay) {
    console.log('No external display detected')
    return
  }
  // Create a window on the secondary display
  let secondaryWin = new BrowserWindow({
    x: externalDisplay.bounds.x,
    y: externalDisplay.bounds.y,
    width: externalDisplay.bounds.width,
    height: externalDisplay.bounds.height,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: true,
      preload: path.join(
        process.cwd(),
        isDevelopment ? 'src/preload-secondary.js' : 'resources/src/preload-secondary.js'
      ),
      webSecurity: false
    },
    kiosk: !isDevelopment,
    frame: isDevelopment,
    fullscreen: !isDevelopment
  })

  // Load the URL in the secondary window
  loadUrl(secondaryWin, url)

  if (isDevelopment) {
    setTimeout(() => {
      secondaryWin.webContents.openDevTools()
    }, 2000)
  }

  secondaryWin.on('closed', () => {
    secondaryWin = null
  })
  clearCache(secondaryWin)
}

export function clearCache(win) {
  return
  // 清除所有缓存
  win.webContents.session.clearCache()
  win.webContents.session.clearStorageData()

  // 禁用缓存加载页面
  // win.loadURL('http://client.smartorderkiosk.com/desk', {
  //   extraHeaders: 'pragma: no-cache\n'
  // })

  // 监听请求禁用缓存
  win.webContents.session.webRequest.onBeforeSendHeaders((details, callback) => {
    details.requestHeaders['Cache-Control'] = 'no-cache'
    callback({ requestHeaders: details.requestHeaders })
  })
}

//加载页面
export function loadUrl(_win, url) {
  if (url.startsWith('http')) {
    _win.loadURL(`${url}${url.includes('?') ? '&' : '?'}t=${Date.now()}`, {
      userAgent: userAgent
    })
  } else {
    _win.loadFile(url, {
      userAgent: userAgent
    })
  }
}
